package com.zbkj.common.core;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import com.tiangong.framework.util.redis.RedisUtil;
import com.zbkj.business.core.minio.MinioConfig;
import com.zbkj.business.core.minio.MinioUtils;
import com.zbkj.common.response.CommonResult;
import com.zbkj.common.utils.BaiDu;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 统一文件上传工具
 * </p>
 *
 * @Author damin
 * @since 2021-09-26
 */
@Slf4j
@RestController
@RequestMapping("/api/sys/common")
public class CommonController {

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig minioConfig;


    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/imageAnalysis")
    public Object imageAnalysis(@RequestParam("file") String file) {
        String imageAnalysis ="";
        try {
            imageAnalysis = BaiDu.callOCRAPI(file);
        } catch (Exception e) {
            log.error("解析失败");
            imageAnalysis ="解析失败";
        }
        return imageAnalysis;
    }
    /**
     * 文件上传
     *
     * @param file
     */
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        try {
            //文件名
            String fileName = file.getOriginalFilename();
            String newFileName = System.currentTimeMillis() + "." + org.apache.commons.lang.StringUtils.substringAfterLast(fileName, ".");
            //类型
            String contentType = file.getContentType();
            minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);
            return CommonResult.success(minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + newFileName);
//            return CommonResult.success();
        } catch (Exception e) {
            log.error("上传失败");
            return CommonResult.failed("上传失败");
        }
    }

    @RequestMapping("/uploadImg")
    public Object uploadImg(@RequestParam(required = true) MultipartFile file,Boolean compress) {
        Return ret=null;
        try {
            ret= OSSUtils.getInstance().upload(file,compress);
        }catch (Exception e){
            ret= Return.EXCEPTION;
            e.printStackTrace();
            log.error("{}",e);
        }
        if(ret.getCode()==0){
            return CommonResult.success(ret.getData());
        }else {
            return CommonResult.failed(ret.getMsg());
        }
    }
    @RequestMapping("/getSTS")
    public Object getSTS() {
        Return ret=null;
        try {
            ret= OSSUtils.getInstance().getSTS();
        }catch (Exception e){
            ret= Return.EXCEPTION;
            e.printStackTrace();
            log.error("{}",e);
        }
        if(ret.getCode()==0){
            return CommonResult.success(ret.getData());
        }else {
            return CommonResult.failed(ret.getMsg());
        }
    }

    @PostMapping(value = "/uploadErpGoodsInfoExcel")
    public CommonResult uploadErpGoodsInfoExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile mfile = multipartRequest.getFile("file");// 获取上传文件对象
        log.info("文件长度:{}", mfile.getSize());
        String[] fileInfo = mfile.getOriginalFilename().split("\\.");
        String fileFormat = fileInfo[fileInfo.length - 1];
        String fileSourceName = fileInfo[fileInfo.length - 2];
        if (!fileFormat.equalsIgnoreCase("xlsx") && !fileFormat.equalsIgnoreCase("csv")) {
            return CommonResult.failed( "订单格式不符合规则");
        }

        InputStream fileInputStream = mfile.getInputStream();

        List<Object> objectsList = new ArrayList<>();
        objectsList= EasyExcel.read(fileInputStream).excelType(ExcelTypeEnum.CSV)//.charset(Charset.forName("GBK"))
                .sheet(0).doReadSync();;
        objectsList.stream().map(CDO::parseObject).filter(cdo -> cdo.getStringValue("12").equals("成功")).forEach(cdo -> {
            CDO cdoRequest = CDO.newRequest("gameorderreportdetail", "save")
                    .set("date", cdo.getStringValue("9").substring(0, 10))
                    .set("id", cdo.getStringValue("0"))
                    .set("gamename", cdo.getStringValue("1"))
                    .set("gameuser", cdo.getStringValue("17"))
                    .set("gamearea", cdo.getStringValue("16"))
                    .set("realname", cdo.getStringValue("24"))
                    .set("username", cdo.getStringValue("4"))
                    .set("useruid", cdo.getStringValue("6"))

                    .set("paytype", cdo.getStringValue("8"))
                    .set("payamount", cdo.getStringValue("7"))
                    .set("channel", cdo.getStringValue("3"))
                    .set("source", "default")
                    .set("userid", "")
                    .set("createtime", cdo.getStringValue("9"));
            String stringValue = cdo.getStringValue("4");

            Return ret = CDO.newRequest("userEntity", "list")
                    .set("userphone", stringValue).setIgnoreLog(true).handleService();
            List<CDO> datalist = ret.getData().getCDOListValue("datalist");
            if(datalist.size() > 0){
                cdoRequest.set("source",datalist.get(0).getStringValue("mark"));
                cdoRequest.set("userid",datalist.get(0).getStringValue("userid"));
            }
            cdoRequest.handleService();

        });
        return CommonResult.success();
    }

    /**
     * 发送验证码
     * @param mobile
     * @param type
     * @return
     */
    @RequestMapping("/sendCode")
    public CommonResult sendCode(String mobile, @RequestParam(required = false) Integer type){
        String code = RandomStringUtils.random(6, false, true);
//        Return aReturn = CDO.newRequest("config", "getConfigById").set("id", 4).handleService();
//        CDO data = aReturn.getData();
//        int type=data.getIntValue("type");
//        int hx=data.getIntValue("hx");
//        int ali=data.getIntValue("ali");
        if(type==null){
            type=1;
        }
        Boolean bOk=false;
        Boolean aBoolean = RedisUtil.getInstance().setNx("LOCK:CODE:" + mobile, "", 60);
        if(!aBoolean){
            return CommonResult.failed("获取验证码频繁，请60秒后再试");
        }

        bOk=OssSms.getInstance().sendSms(mobile,code,1);
        if(!bOk){
            return CommonResult.failed("获取验证码失败");
        }
        RedisUtil.getInstance().set("CODE:" + mobile+":"+type, code, 600);
        return CommonResult.success();
    }

    /**
     * 校验验证码
     * @param mobile
     * @param type
     * @param code
     * @return
     */
    public static boolean checkCode(String mobile, int type, String code){
        String s = RedisUtil.getInstance().get("CODE:" + mobile + ":" + type);
        if(StringUtils.isBlank(s)||!code.equals(s)){
            return false;
        }
        return true;
    }
}
